﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using zqdn.Models.ProvinceCity;
using zqdn.Services.Interfaces.ProvinceCity;

namespace zqdn.Web.Controllers
{
    /*放置一些公共方法 如省份、城市、获取用户信息等*/
    public  class  ApiController : Controller
    {
        #region 获取省份、城市信息
         private  readonly ICityDetailsService _cityDetailservice;

         //ICityDetailsService cityDetailservice, IUserService userservice
         public ApiController()
        {
             _cityDetailservice = DependencyResolver.Current.GetService<ICityDetailsService>();
             //_userservice = DependencyResolver.Current.GetService<IUserService>();
            //this._cityDetailservice = cityDetailservice;
            //this._userservice = userservice;
        }
        // GET: province
        public  IList<CityDetails> GetProvince()
        {
            return _cityDetailservice.GetByDepth(0);
        }

        // GET: city
        public  string GetCity(int pid)
        {
            IList<CityDetails> result = _cityDetailservice.GetByParentID(pid);
            StringBuilder sb = new StringBuilder();
            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            jss.Serialize(result, sb);
            return sb.ToString();
        }

        // GET: hospital
        public string GetHospital(int cid)
        {
            IList<Hospital> result = _cityDetailservice.GetHospitalByCID(cid);
            StringBuilder sb = new StringBuilder();
            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            jss.Serialize(result, sb);
            return sb.ToString();
        }

        // GET: assist
        public string GetAssist(int roleid,int hid)
        {

            return "";
        }

        #endregion

        #region 附件上传
        /// <summary>
        /// 上传资质证书
        /// </summary>
        /// <param name="imageUpLoad"></param>
        /// <returns></returns>
        [HttpPost]
        public  JsonResult  UploadApprove(HttpPostedFileBase imageUpLoad)
        {
            ///上传附件
            string upaddress = string.Empty;
            var c = Request.Files[0];
            if (c == null && c.ContentLength <= 0)
            {
                return Json(new { Result = "error", msg = "服务异常" });
            }
            else
            {

                    string fileName = c.FileName;
                    string newFilename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(0, 9) + fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));

                    string savepath = "/Upload/" + DateTime.Now.Date.ToString("yyyy") + "/" + DateTime.Now.Date.ToString("MMdd");
                    string path = Server.MapPath("~") + savepath;

                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }

                    try
                    {
                        c.SaveAs(path + "/" + newFilename);
                        upaddress += savepath + "/" + newFilename;

                        return Json(new { Result = "success", msg = "上传成功",uploadResult = upaddress });
                    }
                    catch (Exception ex)
                    {
                        return Json(new { Result = "error", msg = ex.ToString() });
                    }

            }
         
        }
        #endregion

        #region 发送短信
        [AllowAnonymous]
        [HttpPost]
        public  ActionResult GetVerifyCode(string mobile, string t = "RegitCode")
        {
            try
            {
                var start = Session["yfc.get_verify_code.last_time"] as DateTime?;
                //if (start.HasValue)
                //{
                //    var df = DateTime.Now - start.Value;
                //    if (df.TotalSeconds < 60)
                //        return Json(new { Result = "error", msg = "两次验证码获取间隔不能少于60秒, 请稍后重试!" });
                //}
                Session["yfc.get_verify_code.last_time"] = DateTime.Now;
                if (string.IsNullOrEmpty(mobile))
                {
                    return Json(new { Result = "error", msg = "请输入手机号！" });
                }
                else
                {
                    Random rad = new Random();
                    int ranint = rad.Next(9999);
                    Session[t] = ranint;
                    string message = "【医途平台】您的验证码是" + ranint;
                    if (Request.IsLocal)
                    {
                        return Json(new { Result = "success", msg = "本地请求, 您的验证码是: " + ranint });
                    }
                    Helpers.YunPianSmsHelper.SendSms(message, mobile);
                    return Json(new { Result = "success", msg = "验证码已发送至您的手机，请注意查收！" });

                }
            }
            catch (Exception ex)
            {
                throw new Exception("发送邮件失败！");
            }
        }


        #endregion

        #region 设置select的值
        public List<SelectListItem> SetOptionItem<T>(IList<T> t,int? selected)
        {
            List<SelectListItem> selectItems = new List<SelectListItem>();
            selectItems.Add(new SelectListItem() { Text = "请选择...", Value = "", Selected = true });
            Type t1 = typeof(T);
            PropertyInfo[] propInfos = t1.GetProperties().Where(o =>o.Name=="ID" || o.Name=="Name").ToArray();
            var key = "";
            var value = "";
            foreach (T item in t)
            {
                SelectListItem itemval = new SelectListItem();
                foreach (var pi in propInfos)
                {
                    key = pi.Name;
                    value = pi.GetValue(item, null).ToString();
                    if (key == "ID")
                    {
                        if (value == selected.ToString())
                        {
                            itemval.Selected = true;
                        }
                        itemval.Value = value.ToString();
                    }
                    else
                    {
                        itemval.Text = value.ToString();
                    }
                }
            
                selectItems.Add(itemval);
            }
           
            return selectItems;

        }
        #endregion
    }
}